#!/bin/bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/fs_utils.sh"

cmd=$( basename "$0" )

function usage() {
	echo "Usage: ${cmd} [ -t | -h | -n | -m]"
    echo "索引CloudCompare的qCC工具源代码"
    echo -e "\t-t: 增加对test代码的索引"
    echo -e "\t-n: dry-run"
    echo -e "\t-m: 增加对cmake文件的索引"
    echo -e "\t-h: 显示帮助信息"
	exit 1
}

function build_file_list() {
    # 重置文件列表
    echo > "${csFile}"
    for d in "${hppDirs[@]}"
    do
        find "$d" ${pruneOpt} ${findTestOpt} -name "*.hpp" -type f -print >> "${csFile}"
        find "$d" ${pruneOpt} ${findTestOpt} -name "*.h" -type f -print >> "${csFile}"
    done
    
    for d in "${cppDirs[@]}"
    do
        find "$d" ${pruneOpt} ${findTestOpt} -name "*.cpp" -type f -print >> "${csFile}"
        find "$d" ${pruneOpt} ${findTestOpt} -name "*.c" -type f -print >> "${csFile}"
        find "$d" ${pruneOpt} ${findTestOpt} -name "*.cc" -type f -print >> "${csFile}"
    done

    if ${buildCmake}
    then
        echo "CMakeLists.txt" >> "${csFile}" 
        for d in "${cmakeDirs[@]}"
        do
            find "$d" ${pruneOpt} ${findTestOpt} -name "*.cmake" -type f -print >> "${csFile}"
            find "$d" ${pruneOpt} ${findTestOpt} -name "CMakeLists.txt" -type f -print >> "${csFile}"
        done
    fi
}

function echo_build_cmd() {
    for d in "${hppDirs[@]}"
    do
        echo find "$d" ${pruneOpt} ${findTestOpt} -name "*.hpp" -type f -print 
        echo find "$d" ${pruneOpt} ${findTestOpt} -name "*.h" -type f -print 
    done
    
    for d in "${cppDirs[@]}"
    do
        echo find "$d" ${pruneOpt} ${findTestOpt} -name "*.cpp" -type f -print 
        echo find "$d" ${pruneOpt} ${findTestOpt} -name "*.c" -type f -print 
        echo find "$d" ${pruneOpt} ${findTestOpt} -name "*.cc" -type f -print 
    done

    if ${buildCmake}
    then
        for d in "${cmakeDirs[@]}"
        do
            echo find "$d" ${pruneOpt} ${findTestOpt} -name "*.cmake" -type f -print 
            echo find "$d" ${pruneOpt} ${findTestOpt} -name "CMakeLists.txt" -type f -print 
        done
    fi
}

# 包括.c,.cc文件所在目录
cppDirs=(qCC plugins libs)
# 包含.h文件所在目录
hppDirs=(qCC plugins libs)
# cmake文件
cmakeDirs=(qCC plugins libs)

# 去掉不需要的EP代码
# pruneOpt="-wholename */providers/acl -type d -prune -o "
# pruneOpt="-wholename */providers/armnn -type d -prune -o ${pruneOpt}"
# 默认不索引test目录下的文件
findTestOpt="-name test -type d -prune -o -name tests -type d -prune -o"
dryRun=false
buildCmake=false
while getopts "tnmh" args
do
    case "${args}" in 
        t)
            findTestOpt=""
            ;;
        n)
            dryRun=true
            ;;
        m)
            buildCmake=true
            ;;
        *)
            usage;;
    esac
done

if ${dryRun}
then
    echo_build_cmd
else
    csFile="cscope.files"
    echo "Build ${csFile} ..."
    build_file_list
    # 建立cscope数据库
    echo "Build cscope DB..."
    cscope -Rbqk
    echo "Done."
fi
